<template>
  <el-card class="box-card">
    <!--面包屑导航区</h3>-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>管理</el-breadcrumb-item>
      <el-breadcrumb-item>订单管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!--搜索框-->
    <div style="display: flex; align-items: center;">
      <el-input placeholder="请输入订单号" style="width: 250px" v-model="orderNumber">
        <el-button slot="append" icon="el-icon-search" @click="searchOrderByNum"></el-button>
      </el-input>
      <div style="margin-left: 10px;">
          <el-select v-model="hotelId" placeholder="请选择酒店">
            <el-option
                v-for="hotel in hotelList"
                :key="hotel.id"
                :label="hotel.hotelName"
                :value="hotel.id">
            </el-option>
          </el-select>
          <el-button icon="el-icon-search" @click="searchOrderByHotel"></el-button>
      </div>
      <div style="margin-left: 10px;">
        <el-input placeholder="请输入用户名" style="width: 250px" v-model="username">
          <el-button slot="append" icon="el-icon-search" @click="searchByUsername"></el-button>
        </el-input>
      </div>
      <!--重置-->
      <el-button type="success" style="margin-left: 30px;" @click="reset">重置</el-button>
    </div>
    <!--表格-->
    <el-table
        stripe
        :data="orderList"
        border
        height="600px"
        style="width: 100%">
      <el-table-column width="60px" type="index"></el-table-column>
      <el-table-column align="center" prop="username" label="用户" width="80"></el-table-column>
      <el-table-column align="center" prop="orderNumber" label="订单号" width="160"></el-table-column>
      <el-table-column align="center" prop="hotelName" label="酒店名" width="150"></el-table-column>
      <el-table-column align="center" prop="roomType" label="类型" width="80">
        <template slot-scope="scope">
          {{ scope.row.roomType ? '标间' : '大床房' }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="roomPrice" label="价格" width="80"></el-table-column>
      <el-table-column align="center" prop="roomNumber" label="房间号" width="80"></el-table-column>
      <el-table-column align="center" prop="orderStatus" label="订单状态" width="80">
        <template slot-scope="scope">
          {{ getOrderStatus(scope.row.orderStatus) }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="hotelCity" label="所在城市" width="80"></el-table-column>
      <el-table-column align="center" prop="hotelAddress" label="地址" width="180"></el-table-column>
      <!--      <el-table-column align="center" width="80" label="完成订单">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-button type="success"  size="mini" v-if="scope.row.orderStatus!==4" >完成</el-button>-->
      <!--          <el-button type="info"  size="mini" v-if="scope.row.orderStatus===4" disabled>已完成</el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->

      <!--      操作-->
      <!--      <el-table-column-->
      <!--          align="left" label="操作" width="300">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-button type="success"  size="mini" v-if="scope.row.orderStatus===1" @click="checkIn(scope.row)">确认入住</el-button>-->
      <!--          <el-button type="success"  size="mini" v-else-if="scope.row.orderStatus===3" disabled>已经入住</el-button>-->
      <!--          <el-button type="info"  size="mini" v-else disabled>不能入住</el-button>-->

      <!--          <el-button type="info"  size="mini" @click="toShowDialog(scope.row)">详情</el-button>-->

      <!--          <el-button type="success"  size="mini" v-if="scope.row.orderStatus===0" @click="refund(scope.row,'取消')">取消</el-button>-->
      <!--          <el-button type="danger"  size="mini" v-else-if="scope.row.orderStatus===1" @click="refund(scope.row,'退款')">退款</el-button>-->
      <!--          <el-button type="danger"  size="mini" v-else-if="scope.row.orderStatus===3" @click="refund(scope.row,'完成')">完成</el-button>-->
      <!--          <el-button disabled  size="mini" v-else-if="scope.row.orderStatus===2">已取消</el-button>-->

      <!--          <el-button type="warning"  size="mini" v-if="scope.row.orderStatus===0" @click="pay(scope.row)">支付</el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column align="left" label="操作" width="250">
        <template slot-scope="scope">
          <!-- 详情按钮在所有状态下都是可用的 -->
          <el-button type="info" size="mini" @click="toShowDialog(scope.row)">详情</el-button>
          <!-- 当订单未支付时（orderStatus===0） -->
          <el-button type="success" size="mini" v-if="scope.row.orderStatus === 0" @click="pay(scope.row)">支付
          </el-button>
          <el-button type="success" size="mini" v-if="scope.row.orderStatus === 0" @click="refund(scope.row, '取消')">
            取消
          </el-button>

          <!-- 当订单已支付时（orderStatus===1） -->
          <el-button type="success" size="mini" v-if="scope.row.orderStatus === 1" @click="checkIn(scope.row)">
            确认入住
          </el-button>
          <el-button type="danger" size="mini" v-if="scope.row.orderStatus === 1" @click="refund(scope.row, '退款')">
            退款
          </el-button>

          <!-- 当订单已取消时（orderStatus===2），按钮禁用 -->
          <el-button disabled size="mini" v-if="scope.row.orderStatus === 2">已取消</el-button>

          <!-- 当订单已入住时（orderStatus===3），提供“完成”操作，但通常不会提供“退款” -->
          <el-button type="info" size="mini" v-if="scope.row.orderStatus === 3" @click="completeOrder(scope.row)">完成
          </el-button>
          <el-button disabled size="mini" v-else-if="scope.row.orderStatus === 3">已经入住</el-button>

          <!-- 当订单已完成时（orderStatus===4），按钮通常禁用，或者可以提供其他操作 -->
          <el-button disabled size="mini" v-if="scope.row.orderStatus === 4">已完成</el-button>

        </template>
      </el-table-column>
    </el-table>
    <!--分页框-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[10,15,20,30]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next"
        :total="total">
    </el-pagination>
    <!--详细描述框-->
    <el-dialog
        :visible.sync="showDialog"
        width="50%"
        @close="showDialog = false"
    >
      <el-descriptions title="订单" :column='1'>
        <el-descriptions-item label="订单号">{{ orderData.orderNumber }}</el-descriptions-item>
        <!--        <el-descriptions-item label="订单状态">{{ orderData.orderStatus === 0 ? '未支付' : '已支付' }}</el-descriptions-item>-->
        <el-descriptions-item label="订单状态">{{ getOrderStatus(orderData.orderStatus) }}</el-descriptions-item>
        <el-descriptions-item label="购买人">{{ orderData.username }}</el-descriptions-item>
        <el-descriptions-item label="房间号">{{ orderData.roomNumber }}</el-descriptions-item>
        <el-descriptions-item label="房间类型">{{ orderData.roomType === '0' ? '大床房' : '标间' }}
        </el-descriptions-item>
        <el-descriptions-item label="价格">{{ orderData.roomPrice }}</el-descriptions-item>
        <el-descriptions-item label="酒店名">{{ orderData.hotelName }}</el-descriptions-item>
        <el-descriptions-item label="联系地址">{{ orderData.hotelAddress }}</el-descriptions-item>
        <el-descriptions-item label="酒店所在城市">{{ orderData.hotelCity }}</el-descriptions-item>
        <el-descriptions-item label="酒店电话">{{ orderData.hotelPhone }}</el-descriptions-item>
        <el-descriptions-item label="入住日期">{{ formatDate(orderData.checkInDate) }}</el-descriptions-item>
        <el-descriptions-item label="离店日期">{{ formatDate(orderData.checkOutDate) }}</el-descriptions-item>
        <el-descriptions-item label="订单生成时间">{{ formatDate(orderData.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="订单更新时间">{{ formatDate(orderData.createTime) }}</el-descriptions-item>
      </el-descriptions>
      <el-button type="primary" @click="showDialog=false">返回</el-button>
    </el-dialog>
  </el-card>
</template>

<script>
import axios from "axios";

export default {
  name: 'OrderTable',
  data() {
    return {
      orderList: [],
      showDialog: false,
      orderData: {
        checkInDate: "",
        checkOutDate: "",
        hotelAddress: "",
        hotelCity: "",
        hotelName: "",
        hotelPhone: "",
        orderNumber: "",
        orderStatus: '',
        roomNumber: "",
        roomPrice: '',
        roomType: '',
        username: "",
        createTime: "",
        updateTime: "",
      },
      //计算订单状态
      getOrderStatus(status) {
        switch (status) {
          case 0:
            return '未支付';
          case 1:
            return '已支付';
          case 2:
            return '已取消';
          case 3:
            return '已入住';
          case 4:
            return '已完成'
          default:
            return '未知状态';
        }
      },
      //分页数据
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 10,
      },
      //总数
      total: 0,
      //订单号条件查询
      orderNumber: '',
      //酒店名
      hotelList: {},
      //酒店id
      hotelId: '',
      //用户名‘
      username:'',
    }
  },
  methods: {
    //格式化时间显示
    formatDate(dateTimeString) {
      const dateTime = new Date(dateTimeString);
      // 检查日期是否有效
      if (isNaN(dateTime.getTime())) {
        return 'Invalid Date';
      }
      // 返回一个格式化的日期时间字符串，不包含秒和时区
      // 使用toLocaleString或自定义格式化方法
      return dateTime.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        hour12: false // 使用24小时制
      }).replace(/\//g, '-').replace(',', ''); // 根据需要替换字符或进一步格式化
    },
    //初始化获取所有订单
    async getOrderList() {
      const urlBase = '/api/order/all';
      const pageSize = this.queryInfo.pageSize;
      const pageNum = this.queryInfo.pageNum;
      const orderNumber = this.orderNumber;
      const hotelId=this.hotelId
      const username=this.username
      let queryParams = `pageSize=${pageSize}&pageNum=${pageNum}`;
      if (orderNumber) {
        queryParams += `&orderNumber=${orderNumber}`;
      }
      if (hotelId){
        queryParams += `&hotelId=${hotelId}`;
      }
      if (username){
        queryParams += `&username=${username}`;
      }
      const url = `${urlBase}?${queryParams}`;
      const {data: res} = await axios.get(url)
      if (res.code !== 0) {
        this.$message.error(res.description || res.message || "请稍后重试");
        return
      }
      this.orderList = res.data.rows;
      this.total = res.data.total;
    },
    //显示详情展示框
    toShowDialog(row) {
      this.showDialog = true;
      this.orderData = {...row};
    },
    //确认入住
    async checkIn(row) {
      const {data: res} = await axios.post('/api/order/setStatus', {
        id: row.id,
        orderStatus: 3,
        roomId: row.roomId,
      });
      if (res.code !== 0) {
        this.$message.error(res.description || "修改失败,请稍后重试");
        return
      }
      await this.getOrderList();
    },
    //退款和取消
    async refund(row, string) {
      const {data: res} = await axios.post('/api/order/setStatus', {
        id: row.id,
        orderStatus: 2,
        roomId: row.roomId,
      });
      if (res.code !== 0) {
        this.$message.error(res.description || "请联系酒店");
        return
      }
      if (string === '退款')
        this.$message.success("订单退款成功")
      else
        this.$message.success("订单取消成功")
      await this.getOrderList();
    },
    //支付
    async pay(row) {
      const {data: res} = await axios.post('/api/order/setStatus', {
        id: row.id,
        orderStatus: 1,
        roomId: row.roomId,
      });
      if (res.code !== 0) {
        this.$message.error(res.description || "请联系酒店");
        return
      }
      this.$message.success("订单支付成功")
      location.reload();
    },
    //订单完成
    async completeOrder(row) {
      const {data: res} = await axios.post('/api/order/setStatus', {
        id: row.id,
        orderStatus: 4,
        roomId: row.roomId,
      });
      if (res.code !== 0) {
        this.$message.error(res.description || "请联系酒店");
        return
      }
      this.$message.success("订单以设置完成")
      location.reload();
    },
    //当前页显示条数改变
    handleSizeChange(val) {
      this.queryInfo.pageSize = val
      this.getOrderList()
    },
    //当前页数改变
    handleCurrentChange(val) {
      this.queryInfo.pageNum = val;
      this.getOrderList()
    },
    //根据订单号查找
    searchOrderByNum() {
      this.hotelId = ''
      this.username=''
      this.getOrderList();
    },
    //根据酒店id查找
    searchOrderByHotel(){
      this.orderNumber=''
      this.username=''
      this.getOrderList();
    },
    //根据用户名获取订单
    searchByUsername() {
      this.hotelId=''
      this.orderNumber=''
      this.getOrderList()
    },
    //获取酒店信息
    async getHotelList() {
      const {data: res} = await axios.get('/api/hotel/search')
      if (res.code!==0){
        this.$message.error(res.msg);
        return
      }
      this.hotelList = res.data.map(hotel => ({ ...hotel, roomCount: null ,minPrice: null,maxPrice: null }));
      // console.log(res)
    },
    reset(){
      this.orderNumber=''
      this.hotelId = ''
      this.username=''
      this.getOrderList()
    }
  },
  mounted() {
    this.getOrderList();
    this.getHotelList()
  }
}
</script>

<style scoped>

</style>